﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace PServiceBus.Core.Runtime.Configuration {
    public class ConfigurationFactory {
        public static TConfigSection GetConfigSection<TConfigSection>() where TConfigSection : ConfigurationSection {
            var configSection = ServiceLocator<TConfigSection>.Get();
            if (configSection != null) return configSection;
            var configuration = default(System.Configuration.Configuration);
            var ex = MethodHelper.Try(() => configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
            if (ex != null)
                ex = MethodHelper.Try(() => configuration = System.Web.Configuration.WebConfigurationManager
                    .OpenWebConfiguration(System.Web.HttpContext.Current.Request.Path));
            if (configuration == null) return configSection;
            var sections = configuration.Sections;
            for (var i = 0; i < sections.Count; i++) {
                var section = sections[i] as TConfigSection;
                if (section == null) continue;
                configSection = section;
                break;
            }
            ServiceLocator<TConfigSection>.Set(configSection);
            return configSection;
        }
    }
}
